package com.knightboy.smartshoes.myUi;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.knightboy.smartshoes.R;
import com.knightboy.smartshoes.coreUtil.LocationHelper;
import com.knightboy.smartshoes.coreUtil.SenserData;
import com.knightboy.smartshoes.coreUtil.SharedData;
import com.knightboy.smartshoes.myView.CircularImage;
import com.knightboy.smartshoes.outerNavigation.MakeUrl;
import com.knightboy.smartshoes.outerNavigation.OuterLocationService;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by knightBoy on 2015/7/17.
 */
public class FirstActivity extends Activity {
    String TAG = "test";
    private int mRecvDataCount;

    // Array adapter for the conversation thread
    private ArrayAdapter<String> mConversationArrayAdapter;

    //退出时间
    private long mExitTime;
    //按钮，文本框的声明,弹出框
    private Button today_bt, inner_bt, outer_bt, more_bt, back_bt, start_bt;
    private TextView calorie_tv, step_tv, rate_tv, minute_tv, weight_tv, time_tv, suggestion_tv, state_tv;
    private EditText from_et, to_et;
    private CircularImage photo_ci;
    //室内导航弹出框
    private AlertDialog selfdialog;
    //室外导航弹出框
    private AlertDialog outerdialog;
    //提醒休息弹出框
    private AlertDialog breakdialog;
    //更多设置的弹出菜单栏
    private PopupWindow mPopupWindow;

    //室内导航存储起点，终点的字符
    private char fromChar, toChar;
    //室外导航终点字符串
    private String destinationStr;

    //BLE设备的地址，名称
    final String mDeviceAddress = "78:A5:04:63:CF:19";
    //BlueToothLeService服务对象
    private BlueToothLeService mBluetoothLeService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first);
        init();

        //提醒减肥
        Toast.makeText(FirstActivity.this,"你的体重占上周102%，加油减肥哦！",Toast.LENGTH_SHORT).show();
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.first);

        getActionBar().setDisplayHomeAsUpEnabled(true);

        Intent gattServiceIntent = new Intent(this, BlueToothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册广播，接收service中启动的线程发送过来的信息，同时更新UI
        IntentFilter filter = makeGattUpdateIntentFilter();
        this.registerReceiver(mGattUpdateReceiver, filter);

        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
        }else{
            //Toast.makeText(FirstActivity.this,"服务不存在",Toast.LENGTH_SHORT).show();
        }

        //注册监听rssi和室外导航的广播
        IntentFilter rssi_outerfilter = new IntentFilter();
        rssi_outerfilter.addAction("com.knightboy.rssi");
        rssi_outerfilter.addAction("com.knightboy.outer");
        this.registerReceiver(new MyBroadCaseReceiver(),rssi_outerfilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关掉整个程序，主要是服务
        System.exit(0);
    }

    /**
     * 初始化的方法
     */
    private void init(){
        //设置SenserData助手类
        SenserData.setInnerHandler(mHandler);
        SenserData.setFallOrBreakHandler(fallOrBreakHandler);

        //获得个控件的引用
        today_bt = (Button)findViewById(R.id.today_bt);
        inner_bt = (Button)findViewById(R.id.inner_bt);
        outer_bt = (Button)findViewById(R.id.outer_bt);
        more_bt = (Button)findViewById(R.id.more_bt);

        calorie_tv = (TextView)findViewById(R.id.calorie_tv);
        step_tv = (TextView)findViewById(R.id.step_tv);
        rate_tv = (TextView)findViewById(R.id.rate_tv);
        minute_tv = (TextView)findViewById(R.id.minute_tv);
        weight_tv = (TextView)findViewById(R.id.weight_tv);
        time_tv = (TextView)findViewById(R.id.time_tv);
        suggestion_tv = (TextView)findViewById(R.id.suggestion_tv);
        state_tv = (TextView)findViewById(R.id.state_tv);

        photo_ci = (CircularImage)findViewById(R.id.user_photo);
        photo_ci.setImageResource(R.drawable.user);

        //获取系统现在时间
        SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String timeStr = formatter.format(curDate);
        time_tv.setText(timeStr);

        //给更多按钮添加监听器，实现首界面到今日数据界面的跳转
        today_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                forward(TodayActivity.class);
            }
        });

        //更多设置键添加监听器
        more_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPopupWindowInstance();
                mPopupWindow.showAsDropDown(more_bt,13,0);
            }
        });

        //给室内导航按钮添加监听器
        inner_bt.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                //创建view
                LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.inner, null);

                final EditText from_et=(EditText)view.findViewById(R.id.from_et);
                final EditText to_et = (EditText)view.findViewById(R.id.to_et);
                from_et.setText("D");
                to_et.setText("C");
                AlertDialog.Builder ad =new AlertDialog.Builder(FirstActivity.this);
                ad.setView(view);
                ad.setTitle("室内导航");
                selfdialog =ad.create();
                selfdialog.setButton("开始", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //获取输入框的用户名密码
                        fromChar = from_et.getText().toString().charAt(0);
                        toChar = to_et.getText().toString().charAt(0);
                        //开始导航查询路径
                        LocationHelper.getPath(fromChar, toChar);
                        //设置室内导航标志
                        SenserData.setIsNavi(true);
                    }
                });
                selfdialog.setButton2("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        selfdialog.cancel();
                    }
                });
                selfdialog.show();
            }
        });

        //给室外导航按钮添加监听器
        outer_bt.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                //创建view
                LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.outer, null);

                final EditText to_et = (EditText)view.findViewById(R.id.to_et);
                //创建对话框
                AlertDialog.Builder ad =new AlertDialog.Builder(FirstActivity.this);
                ad.setView(view);
                ad.setTitle("室外导航");
                outerdialog =ad.create();
                outerdialog.setButton("开始", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //获取输入框的目的地
                        destinationStr = to_et.getText().toString();
                        //开始室外导航.如果不存在室外导航服务，则开启服务
                        if(!hasServiceForName("com.knightboy.smartshoes.outerNavigation.OuterLocationService")){
                            //设置目的地
                            MakeUrl.setDesString(destinationStr);
                            //启动service
                            Intent intent = new Intent(FirstActivity.this, OuterLocationService.class);
                            FirstActivity.this.startService(intent);
                        }
                    }
                });
                outerdialog.setButton2("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        outerdialog.cancel();
                    }
                });
                outerdialog.show();
            }
        });
    }

    //***********************************Handler*****************************
    /**
     * 接收转向信息的Handler类
     */
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.arg1 == 0){
                String str = "已到达" + LocationHelper.toPlace +"点." + "转向信息:" + LocationHelper.direction;
                FirstActivity.this.sendMessage(LocationHelper.direction);
                Toast.makeText(FirstActivity.this,str,Toast.LENGTH_SHORT).show();

                //创建定时器,一秒后结束震动
                Timer timer = new Timer();
                //创建定时任务
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        FirstActivity.this.sendMessage(0);
                        if(LocationHelper.toPlace == LocationHelper.destination){
                            //Toast.makeText(FirstActivity.this,"导航结束！",Toast.LENGTH_SHORT).show();
                        }else {
                            //再次导航
                            LocationHelper.getPath(LocationHelper.toPlace, LocationHelper.destination);
                            SenserData.setIsNavi(true);
                        }
                    }
                };
                //定时任务启动
                timer.schedule(task, 4000);
            }
        }
    };

    /**
     * 摔倒报警,提醒休息Handler类
     */
    Handler fallOrBreakHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.arg1 == 1){
                final AlertDialog dialog = new AlertDialog.Builder(FirstActivity.this).setTitle("你摔倒了吗？")//.setIcon(R.drawable.fall)
                        .setPositiveButton("是的", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startAlarm();
                                dialog.dismiss();
                            }
                        }).setNegativeButton("不是",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        SenserData.setIsfallen(false);
                    }
                }).create();
                dialog.show();

                //创建定时器,五秒后结报警
                Timer timer = new Timer();
                //创建定时任务
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        if(SenserData.getIsFallen() == true){
                            startAlarm();
                            dialog.dismiss();
                        }
                    }
                };
                //定时任务启动
                timer.schedule(task, 5000);
            }else if(msg.arg1 == 2){
                //提醒用户及时去活动一下
                //创建对话框
                LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.breaktime, null);
                AlertDialog.Builder ad =new AlertDialog.Builder(FirstActivity.this);
                ad.setView(view);
                ad.setTitle("待久了，出去活动一下吧！");
                breakdialog =ad.create();
                breakdialog.setButton("现在就去", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        breakdialog.cancel();
                        SharedData.setLastStepTime();
                        SenserData.setHasAwake(false);
                    }
                });
                breakdialog.setButton2("下次提醒", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        breakdialog.cancel();
                        SharedData.setLastStepTime();
                        SenserData.setHasAwake(false);
                    }
                });
                breakdialog.show();
            }
        }
    };
    //*********************************Handler定义结束*****************************

    //********************************播放系统铃声*********************************

    /**
     * 播放报警音乐
     */
    private void startAlarm() {
        MediaPlayer mMediaPlayer = MediaPlayer.create(this, getSystemDefultRingtoneUri());
        mMediaPlayer.setLooping(false); //不循环，只播放一遍
        try {
            mMediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMediaPlayer.start();
    }

    //获取系统默认铃声的Uri
    private Uri getSystemDefultRingtoneUri() {
        return RingtoneManager.getActualDefaultRingtoneUri(this,
                RingtoneManager.TYPE_RINGTONE);
    }

    //********************************播放系统铃声段结束****************************

    //***************蓝牙部分************************************************************************
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BlueToothLeService.LocalBinder) service).getService();
            if(mBluetoothLeService == null){
                Log.e(TAG,"bbbb");
            }
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up
            // initialization.
            mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    // 处理来自BlueToothLeService发送的广播
    // ACTION_GATT_CONNECTED: 连接上GATT服务器
    // ACTION_GATT_DISCONNECTED: 与GATT服务器断开
    // ACTION_GATT_SERVICES_DISCOVERED: 发现GATT服务器
    // ACTION_DATA_AVAILABLE: 从设备上读到数据，可能是直接读取了或者更新操作
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BlueToothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                updateConnectionState(R.string.connected);
                invalidateOptionsMenu();
                mRecvDataCount = 0;
            } else if (BlueToothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                updateConnectionState(R.string.disconnected);
                invalidateOptionsMenu();
                clearUI();
            }
            //收到了读取到数据的广播后广播接收器执行的操作
            else if (BlueToothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                //读取Rssi数值
                mBluetoothLeService.readRemoteRssi();

                //获得数据,getRecvedData()是同步操作的
                ArrayList<byte[]> arrayList = mBluetoothLeService.getRecvedData();
                int i = 0;
                while ((i++<10) && (arrayList.size() > 0)) {
                    //获得数据队列第一项
                    byte[] data = arrayList.remove(0);

                    //获得20字节的数据项
                    if (data != null && data.length >= 20) {
                        //检查第一个字节和最后一个字节,符合要求就是需要的数据
                        if(data[0] == 83 && data[19] == 90){
                            try{
                                SenserData.handleByteArray(data);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
//                            suggestion_tv.setText(SenserData.getData());
                        }else if(data[0] == 84 && data[11] == 90){
                            SenserData.handleByteArray(data, true);
//                            suggestion_tv.setText(SenserData.getData());
                        }
                        mRecvDataCount += data.length;
                    }
                }
                //更新走路数据
                //更新卡路里数据
                calorie_tv.setText((SharedData.getActiveCalorie() + SharedData.getRestCalorie()) + "" );
                //更新步数
                step_tv.setText((SharedData.getStep())+"");
                //延迟500ms后步数加1
//                mHandler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        String str = step_tv.getText().toString();
//                        int mstep = Integer.parseInt(str);
//                        step_tv.setText((mstep + 1) + "");
//                    }
//                }, 500);
                //更新走路时间
                minute_tv.setText(SharedData.getActiveTime() + "");
//                rate_tv.setText(SharedData.getRate()+"");
//                weight_tv.setText(SharedData.getWeight()+"");
            }
        }
    };

    private void clearUI() {
        mConversationArrayAdapter.clear();
    }

    /**
     * 更新界面的连接状态
     * @param resourceId
     */
    private void updateConnectionState(final int resourceId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    /**
     * 向蓝牙发送数据
     * @param command 要发送的数据，数字字符串
     */
    private void sendMessage(int command) {
        // 检查是否真的建立了连接
        if (mBluetoothLeService.getState() != BlueToothLeService.STATE_CONNECTED) {
            //Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        //根据对应命令生成16进制命令
        byte[] data = new byte[]{0x00};
        switch (command){
            case 0:
                data = new byte[]{0x00};
                break;
            case 1:
                data = new byte[]{0x01};
                break;
            case 2:
                data = new byte[]{0x02};
                break;
            case 3:
                data = new byte[]{0x03};
                break;
            case 4:
                data = new byte[]{0x04};
                break;
            default:
                break;
        }
        //发送16进制的命令
        mBluetoothLeService.write(data);
    }

    /**
     * 生成接收蓝牙数据更新广播的IntentFilter对象
     * @return
     */
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BlueToothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BlueToothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BlueToothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BlueToothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    //****************蓝牙部分结束****************************************************************************


    /**
     * 界面跳转
     */
    private void forward(Class<?> classObj){
        Intent intent = new Intent();
        intent.setClass(this, classObj);
        this.startActivity(intent);
    }

    /**
     * 广播接收器类
     */
    class MyBroadCaseReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent intent) {
            final String rssiAction = "com.knightboy.rssi";
            final String outerAction = "com.knightboy.outer";
            final String action = intent.getAction();
            //根据动作分辨是rssi的广播还是室外导航的广播
            if (rssiAction.equals(action)){
                //手机被盗,手机，鞋垫发生震动
                Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                vibrator.vibrate(2000);
                startAlarm();
                sendMessage(5);
                state_tv.setText(SenserData.getData());
            }else if(outerAction.equals(action)){
                int direction = intent.getIntExtra("direction", 0);
//                sendMessage(direction);
                Toast.makeText(FirstActivity.this,"转向信息:"+ direction,Toast.LENGTH_SHORT).show();
            }
        }
    }

    public boolean hasServiceForName(String serviceName){
        //返回的结果
        boolean result = false;
        //根据服务名字判断是否存在
        ActivityManager myManager=(ActivityManager)FirstActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(30);
        for(int i = 0 ; i<runningService.size();i++)
        {
            if(runningService.get(i).service.getClassName().toString().equals(serviceName))
            {
                //找到符合的服务就返回真
                result = true;
            }
        }
        return result;
    }

    /**
     * 创建右上角菜单
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        if ((mBluetoothLeService != null)
                && (mBluetoothLeService.getState() == BlueToothLeService.STATE_CONNECTED)) {
            menu.findItem(R.id.menu_connect).setVisible(false);
            menu.findItem(R.id.menu_disconnect).setVisible(true);
        } else {
            menu.findItem(R.id.menu_connect).setVisible(true);
            menu.findItem(R.id.menu_disconnect).setVisible(false);
        }
        return true;
    }

    /**
     * 点击右上角菜单执行的事件
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_connect:

                mBluetoothLeService.connect(mDeviceAddress);
                return true;
            case R.id.menu_disconnect:
                mBluetoothLeService.disconnect();
                return true;
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 按两次键才退出程序
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();

            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //*********************************更多弹出菜单项部分******************************
    /*
     * 获取PopupWindow实例
     */
    private void getPopupWindowInstance() {
        if (null != mPopupWindow) {
            mPopupWindow.dismiss();
            return;
        } else {
            initPopuptWindow();
        }
    }

    /*
     * 创建PopupWindow
     */
    private void initPopuptWindow() {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View popupWindow = layoutInflater.inflate(R.layout.setting, null);
        //获得控件
        Button reset_bt = (Button)popupWindow.findViewById(R.id.reset_bt);
        Button setting_bt = (Button)popupWindow.findViewById(R.id.setting_bt);
        Button foot_bt = (Button)popupWindow.findViewById(R.id.foot_bt);
        Button cacel_bt = (Button)popupWindow.findViewById(R.id.cancle_bt);
        //给弹出菜单按钮添加监听器
        reset_bt.setOnClickListener(popupWindowListener);
        setting_bt.setOnClickListener(popupWindowListener);
        foot_bt.setOnClickListener(popupWindowListener);
        cacel_bt.setOnClickListener(popupWindowListener);

        // 创建一个PopupWindow
        // 参数1：contentView 指定PopupWindow的内容
        // 参数2：width 指定PopupWindow的width
        // 参数3：height 指定PopupWindow的height
        mPopupWindow = new PopupWindow(popupWindow, 200, 330);
    }

    View.OnClickListener popupWindowListener = new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.reset_bt:
                    SenserData.reset();
                    SharedData.reset();
                    mPopupWindow.dismiss();
                    break;
                case R.id.setting_bt:
                    mPopupWindow.dismiss();
                    Intent aintent = new Intent(FirstActivity.this,TestActivity.class);
                    startActivity(aintent);
                    break;
                case R.id.foot_bt:
                    mPopupWindow.dismiss();
                    Intent intent = new Intent(FirstActivity.this,FootActivity.class);
                    startActivity(intent);
                    break;
                case R.id.cancle_bt:
                    mPopupWindow.dismiss();
                    break;
                default:
                    mPopupWindow.dismiss();
                    break;
            }
        }
    };

    //*********************************更多弹出菜单项部分结束******************************
}
